package com.huitongmaoyi.ai.service;

import com.huitongmaoyi.ai.dao.ChatDAO;
import com.huitongmaoyi.ai.dao.ChatRoomDAO;
import com.huitongmaoyi.ai.dao.UserDAO;
import com.huitongmaoyi.ai.entity.ChatMessage;
import com.huitongmaoyi.ai.entity.ChatRoom;
import com.huitongmaoyi.ai.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.PrintWriter;

public class ChatRoomService {
    private final Scanner scanner;
    private final String currentUsername;
    private final PrintWriter out;
    private final UserDAO userDAO = new UserDAO();
    private final ChatRoomDAO chatRoomDAO = new ChatRoomDAO();
    private final ChatDAO chatDAO = new ChatDAO();
    private boolean isInChatRoom = false; // 标记是否在聊天室中

    public ChatRoomService(Scanner scanner, String currentUsername, PrintWriter out) {
        this.scanner = scanner;
        this.currentUsername = currentUsername;
        this.out = out;
    }

    /**
     * 进入聊天室主菜单
     */
    public void enterChatRoomMenu() {
        try {
            while (true) {
                out.println("\n=== 聊天室功能 ===");
                out.println("1. 创建聊天室");
                out.println("2. 加入聊天室");
                out.println("3. 我的聊天室");
                out.println("4. 返回上一级");
                out.println("请选择：");
                String choice = scanner.nextLine().trim();

                switch (choice) {
                    case "1":
                        createChatRoom();
                        break;
                    case "2":
                        joinPublicChatRoom();
                        break;
                    case "3":
                        showMyChatRooms();
                        break;
                    case "4":
                        return;
                    default:
                        out.println("无效选项，请重新输入");
                }
            }
        } catch (SQLException e) {
            out.println("聊天室操作失败：" + e.getMessage());
        }
    }

    /**
     * 显示我的聊天室列表
     */
    private void showMyChatRooms() throws SQLException {
        Long userId = userDAO.getUserIdByUsername(currentUsername);
        if (userId == null) {
            out.println("获取用户信息失败");
            return;
        }

        List<ChatRoom> myRooms = chatRoomDAO.getUserRooms(userId);
        if (myRooms.isEmpty()) {
            out.println("您还没有加入任何聊天室");
            return;
        }

        out.println("\n=== 我的聊天室 ===");
        for (int i = 0; i < myRooms.size(); i++) {
            ChatRoom room = myRooms.get(i);
            out.println((i + 1) + ". " + room.getRoomName() + " (ID: " + room.getRoomId() + ") " +
                    (room.isPrivate() ? "[私有]" : "[公开]"));
        }

        out.println("请输入序号进入聊天室（输入0返回）：");
        String choice = scanner.nextLine().trim();
        if ("0".equals(choice)) {
            return;
        }

        try {
            int index = Integer.parseInt(choice) - 1;
            if (index >= 0 && index < myRooms.size()) {
                ChatRoom selectedRoom = myRooms.get(index);
                enterChatRoom(selectedRoom.getRoomId());
            } else {
                out.println("无效序号");
            }
        } catch (NumberFormatException e) {
            out.println("请输入数字");
        }
    }

    /**
     * 进入聊天室
     */
    private void enterChatRoom(long roomId) throws SQLException {
        Long userId = userDAO.getUserIdByUsername(currentUsername);
        if (userId == null) {
            out.println("获取用户信息失败");
            return;
        }

        // 检查是否已加入，未加入则自动加入
        if (!chatRoomDAO.isMember(roomId, userId, null)) {
            joinChatRoom(roomId, userId);
            out.println("已自动加入聊天室");
        }

        String roomName = chatRoomDAO.getRoomName(roomId);
        out.println("\n=== 已进入聊天室：" + roomName + " (ID:" + roomId + ") ===");
        out.println("发送消息格式：直接输入内容（输入「退出」返回）");
        out.println("输入「在线成员」查看当前在线用户");

        isInChatRoom = true;
        // 启动消息监听线程
        startChatRoomListening(roomId);

        // 消息发送循环
        while (isInChatRoom) {
            String message = scanner.nextLine().trim();
            if ("退出".equals(message)) {
                isInChatRoom = false;
                out.println("已退出聊天室");
                break;
            } else if ("在线成员".equals(message)) {
                showOnlineMembers(roomId);
            } else if (!message.isEmpty()) {
                // 发送聊天室消息
                chatDAO.sendRoomMessage(roomId, "user", userId.toString(), message);
                out.println("我：" + message);
            }
        }
    }

    /**
     * 加入聊天室（向数据库插入记录）
     */
    private void joinChatRoom(long roomId, long userId) throws SQLException {
        String sql = "INSERT INTO chat_room_members (room_id, user_id, joined_at) VALUES (?, ?, NOW())";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            stmt.setLong(2, userId);
            stmt.executeUpdate();
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 显示在线成员
     */
    private void showOnlineMembers(long roomId) throws SQLException {
        List<String> onlineMembers = chatRoomDAO.getOnlineMembers(roomId);
        out.println("当前在线成员 (" + onlineMembers.size() + ")：" + onlineMembers);
    }

    /**
     * 创建聊天室
     */
    private void createChatRoom() throws SQLException {
        Long userId = userDAO.getUserIdByUsername(currentUsername);
        if (userId == null) {
            out.println("获取用户信息失败");
            return;
        }

        out.println("请输入聊天室名称：");
        String roomName = scanner.nextLine().trim();
        if (roomName.isEmpty()) {
            out.println("聊天室名称不能为空");
            return;
        }

        out.println("是否创建私有聊天室？(y/n)");
        String isPrivate = scanner.nextLine().trim();
        boolean privateRoom = "y".equalsIgnoreCase(isPrivate);
        String password = null;

        if (privateRoom) {
            out.println("请设置聊天室密码：");
            password = scanner.nextLine().trim();
            if (password.isEmpty()) {
                out.println("私有聊天室密码不能为空");
                return;
            }
        }

        // 创建聊天室（需要在ChatRoomDAO中实现createChatRoom方法）
        long roomId = chatRoomDAO.createChatRoom(roomName, userId, privateRoom, password);
        // 自动加入创建的聊天室
        joinChatRoom(roomId, userId);
        out.println("聊天室创建成功！ID: " + roomId);
    }

    /**
     * 加入公开聊天室
     */
    private void joinPublicChatRoom() throws SQLException {
        // 获取所有公开聊天室（需要在ChatRoomDAO中实现getPublicRooms方法）
        List<ChatRoom> publicRooms = chatRoomDAO.getPublicRooms();
        if (publicRooms.isEmpty()) {
            out.println("暂无公开聊天室");
            return;
        }

        out.println("\n=== 公开聊天室列表 ===");
        for (int i = 0; i < publicRooms.size(); i++) {
            ChatRoom room = publicRooms.get(i);
            out.println((i + 1) + ". " + room.getRoomName() + " (ID: " + room.getRoomId() + ")");
        }

        out.println("请输入序号加入聊天室（输入0返回）：");
        String choice = scanner.nextLine().trim();
        if ("0".equals(choice)) {
            return;
        }

        try {
            int index = Integer.parseInt(choice) - 1;
            if (index >= 0 && index < publicRooms.size()) {
                ChatRoom selectedRoom = publicRooms.get(index);
                Long userId = userDAO.getUserIdByUsername(currentUsername);
                if (userId != null) {
                    joinChatRoom(selectedRoom.getRoomId(), userId);
                    out.println("已加入聊天室：" + selectedRoom.getRoomName());
                }
            } else {
                out.println("无效序号");
            }
        } catch (NumberFormatException e) {
            out.println("请输入数字");
        }
    }

    /**
     * 启动消息监听线程
     */
    private void startChatRoomListening(long roomId) {
        new Thread(() -> {
            try {
                long lastMessageId = getLastMessageId(roomId); // 获取当前最后一条消息ID
                while (isInChatRoom) {
                    Thread.sleep(2000); // 每2秒检查一次新消息
                    List<ChatMessage> newMessages = getNewMessages(roomId, lastMessageId);

                    if (!newMessages.isEmpty()) {
                        out.println("\n--- 新消息 ---");
                        for (ChatMessage msg : newMessages) {
                            // 在startChatRoomListening方法中
                            String senderName = userDAO.getUsernameByUserId(Long.parseLong(msg.getSenderId()));
                            out.println(senderName + "：" + msg.getContent());
                            lastMessageId = msg.getMessageId(); // 更新最后一条消息ID
                        }
                        out.println("--------------");
                        out.print("请输入消息：");
                        out.flush(); // 刷新输出流
                    }
                }
            } catch (Exception e) {
                if (isInChatRoom) { // 只有在聊天室中时才显示错误
                    out.println("消息监听异常：" + e.getMessage());
                }
            }
        }).start();
    }

    /**
     * 获取聊天室最后一条消息ID
     */
    private long getLastMessageId(long roomId) throws SQLException {
        String sql = "SELECT MAX(message_id) as last_id FROM chat_messages WHERE room_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getLong("last_id");
            }
            return 0;
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 获取聊天室新消息
     */
    private List<ChatMessage> getNewMessages(long roomId, long lastMessageId) throws SQLException {
        String sql = "SELECT * FROM chat_messages " +
                "WHERE room_id = ? AND message_id > ? " +
                "ORDER BY sent_at ASC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            stmt.setLong(2, lastMessageId);
            ResultSet rs = stmt.executeQuery();

            List<ChatMessage> messages = new ArrayList<>();
            while (rs.next()) {
                ChatMessage msg = new ChatMessage();
                msg.setMessageId(rs.getLong("message_id"));
                msg.setRoomId(roomId);
                msg.setSenderType(rs.getString("sender_type"));
                msg.setSenderId(rs.getString("sender_id"));
                msg.setContent(rs.getString("content"));
                msg.setSentAt(rs.getTimestamp("sent_at").toLocalDateTime());
                messages.add(msg);
            }
            return messages;
        } finally {
            DBUtil.closeConnection();
        }
    }
}